package com.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.dto.Result;
import com.entity.BrowsingHistroy;
import com.entity.User;
import com.service.UserService;
import com.util.BrowseUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import com.service.BrowsingHistroyService;
import net.sf.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;

/*
 * swagger通过注解表明该接口会生成文档，包括接口名、请求方法、参数、返回信息的等等。
 * @Api：修饰整个类，描述Controller的作用
 * @ApiOperation：描述一个类的一个方法，或者说一个接口
 * @ApiParam：单个参数描述
 * @ApiModel：用对象来接收参数
 * @ApiProperty：用对象接收参数时，描述对象的一个字段
 * @ApiResponse：HTTP响应其中1个描述
 * @ApiResponses：HTTP响应整体描述
 * @ApiIgnore：使用该注解忽略这个API
 * @ApiError ：发生错误返回的信息
 * @ApiParamImplicitL：一个请求参数
 * @ApiParamsImplicit 多个请求参数
 * 访问地址：http://localhost:8080/swagger-ui.html 
 * */

@RestController
@RequestMapping("/user")
public class InterfaceController {
	@Autowired
	private UserService userService;
	@Autowired
	private BrowsingHistroyService BrowsingHistroyService;
	//获取properties文件里面的值
	//@Autowired
	private Properties settings;
	//获取yml文件的值
	@Value("${default.name}")
	private String name;
	@Value("${default.age}")
	private String age;
	
	
	public static ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
	
	//测试mybatis (get方式)
	@ApiOperation(value="测试mybatis (get方式)", notes="测试mybatis (get方式)")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String")
	@RequestMapping(value = "/{id}",method = RequestMethod.GET)
	public Result getUser(@PathVariable("id") String id){
		Result result = new Result();
		try{
			User user =  userService.getUser(id);
			
			if(user!=null){
				JSONObject json = JSONObject.fromObject(user);
				result.setState("0000");
				result.setMsg("处理成功！");
				result.setData(json);
				return result;
			}
			JSONObject json = JSONObject.fromObject(user);
			result.setState("9999"); 
			result.setMsg("处理失败！");
			result.setData(json);
			return result;
			
		}catch(Exception e){
			result.setState("9999"); 
			result.setMsg("操作异常！");
			result.setData(null);
			return result;
		}
		
	}
	
	//post方式
	@ApiOperation(value="根据ID查询", notes="根据ID查询用户")
    @ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User")
    @RequestMapping(value="/postUser", method=RequestMethod.POST)
	public Result postUser(@RequestBody User user) {
		Result result = new Result();
		User user1 =  userService.getUser(user.getId());
		JSONObject json = JSONObject.fromObject(user1);
		result.setState("0000"); 
		result.setMsg("处理成功！");
		result.setData(json);
		return result;
    }
	
	//post方式
	@ApiOperation(value="根据ID修改用户（测试事物Transactional）", notes="根据ID修改用户（测试事物Transactional）")
    @ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User")
    @RequestMapping(value="/Transactional", method=RequestMethod.POST)
	@Transactional
	public Result Transactional(@RequestBody User user) {
		Result result = new Result();
		User user1 =  userService.getUser(user.getId());
		user1.setAge("100");
		userService.updateUser(user1);
		//本年龄应该是100，但加上事物注解后，年龄没有变化
		int i = 1/0;
		System.out.println("异常："+i);
		JSONObject json = JSONObject.fromObject(user1);
		result.setState("0000"); 
		result.setMsg("处理成功！");
		result.setData(json);
		return result;
    }
	
	//获取yml里面配的值
	@ApiOperation(value="获取yml里面配的值", notes="获取yml里面配的值")
    @RequestMapping(value = "/default",method=RequestMethod.GET)
	public Result byUser(){
		Result result = new Result();
		try{
			User user = new User("123",name,age);
			JSONObject json = JSONObject.fromObject(user);
			result.setState("0000"); 
			result.setMsg("处理成功！");
			result.setData(json);
			return result;
		}catch(Exception e){
			result.setState("9999"); 
			result.setMsg("操作异常！");
			result.setData(null);
			return result;
		}
	}
	
	//获取访问者IP及其物理地址
	@ApiOperation(value="获取访问者IP及其物理地址", notes="获取访问者IP及其物理地址")
	@RequestMapping(value = "/properties",method=RequestMethod.GET)
	public Result getProperties(HttpServletRequest request){
		Result result = new Result();
		settings=(Properties)applicationContext.getBean("settings");
		try{
			String imgPath=settings.getProperty("imgPath");
			JSONObject json = new JSONObject();
			json.put("imgPath", imgPath);
			result.setState("0000"); 
			result.setMsg("处理成功！");
			result.setData(json);
			//保存操作记录
			JSONObject obj = new JSONObject();
			BrowsingHistroy browsingHistroy = new BrowsingHistroy();
			obj.put("result", result.toString());
			//获取访问者的物理地址信息及ip
			browsingHistroy = BrowseUtil.getbrowsingHistroy(request);
			obj = JSONObject.fromObject(browsingHistroy);
			saveRecord(obj);
			return result;
		}catch(Exception e){
			result.setState("9999");
			result.setMsg("操作异常！");
			result.setData(null);
			return result;
		}
	}
	
	
	
	
	
	//保存浏览记录
	public void saveRecord(JSONObject jsonObj){
		try {
			String id = UUID.randomUUID().toString().replaceAll("-", "");
			//浏览人姓名
		    String visitorName = "子轩丶破译者";
		    //访问的ip地址
		    //本地访问ip "127.0.0.1"，若用localhost来访问，获取到的会是0:0:0:0:0:0:0:1
		    String visitIpAdd = jsonObj.optString("visitIpAdd");
		    //访问的物理地址
		    String visitphyAdd = jsonObj.optString("visitphyAdd");
		    //访问时间
		    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//设置日期格式
		    String date = df.format(new Date());
		    Date visitTime=df.parse(date);
		    //个人信息
		    String persionInfo = "德玛西亚大军";
		    //创建时间
		    Date createTime = df.parse(df.format(new Date()));
			BrowsingHistroy browsingHistroy = new BrowsingHistroy(id,visitorName,visitIpAdd,visitphyAdd,visitTime,persionInfo,createTime);
			BrowsingHistroyService.insertRecord(browsingHistroy);
			System.out.println("记录插入成功~");
		} catch (Exception e) {
			System.out.println("该条记录保存失败！");
		}
	}

}	
